<template>
  <div class="equipmentMaintenance zy-content">
    <div v-show="!isShowDetails">
      <div class="searchBox search-box-layout">
        <Row :gutter="24">
<!--          <Col span="4">-->
<!--            <div>-->
<!--              <p class="label">{{ $t('spareParts.company') }}</p>-->
<!--              <div class="ipt">-->
<!--                <Select v-model="searchParams.companyId" filterable clearable-->
<!--                        :placeholder="$t('common.PleaseSelect')">-->
<!--                  <Option v-for="(item, index) of companyList"-->
<!--                          :value="item.id"-->
<!--                          :label="item.name"-->
<!--                          :key="index">-->
<!--                  </Option>-->
<!--                </Select>-->
<!--              </div>-->
<!--            </div>-->
<!--          </Col>-->
          <Col span="6">
            <div>
              <p class="label">{{ $t('equipmentscrapped.Location') }}</p>
              <div class="ipt">
                <Cascader :value.sync="searchParams.orgCodes"/>
<!--                <Cascader clearable :data="orgList"-->
<!--                          v-model="orderArr"-->
<!--                          :placeholder="$t('common.PleaseSelect')"-->
<!--                          @on-change="handleCasChange"-->
<!--                          change-on-select ></Cascader>-->
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{ $t('maintenance.EquipmentNo') }}</p>
              <div class="ipt">
                <Select v-model="searchParams.deviceNo"
                        filterable
                        label-in-value
                        clearable
                        :remote-method="searchDevice"
                        :placeholder="$t('maintenance.EquipmentNo')">
                  <Option v-for="(item, index) of deviceList"
                          :value="item.deviceNo"
                          :key="index"
                          :label="item.deviceNo + '-' + item.deviceName">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{ $t('设备等级') }}</p>
              <div class="ipt">
                <Select v-model="searchParams.categoryName" filterable clearable
                        :placeholder="$t('common.PleaseSelect')">
                  <Option v-for="(item, index) of categoryNameList"
                          :value="item"
                          :key="index"
                          :label="item">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{ $t('日期') }}</p>
              <div class="ipt">
                <DatePicker type="daterange"
                            :value="dateTimeRange"
                            :placeholder="$t('common.PleaseSelect')"
                            transfer-class-name="hide-handle-cancel"
                            placement="bottom"
                            transfer
                            :clearable="false"
                            @on-change="handleChangeDate">

                </DatePicker>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" v-has="'equipmentMaintenanceSearch'" type="primary" @click="changeNum()">{{ $t('common.Query') }}</Button>
                <Button v-has="'equipmentMaintenanceSearch'"
                  class="reset-btn"
                  @click="reset()"
                >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>
      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">{{ $t('common.listInformation') }}</span>
          <Button @click="exportTemplateClick">{{ $t('common.batchExport') }}</Button>
            <Button @click="getTableColumns(columns)">
                {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
            </Button>
        </div>
        <div class="tableContent">
          <Table  class="resizable-table" border @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,'equipmentMaintenancepage1')}" :columns="columnsList"  :data="dataSource" @on-selection-change="onSelectChange">
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="showLookTable(row)"><i
                class="iconfont zy-common-chakan"></i>{{ $t('common.Check') }}</span>
              <!-- 查看 -->
            </template>
          </Table>
        </div>
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="ids.length"/>
          <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
                @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
        </div>
      </div>
    </div>
    <div v-if="isShowDetails">
      <!-- 设备维修详情 -->
      <lookTable :label="$t('fault.Generation')"
                 :title="$t('fault.maintenanceDetails')"
                 :id=deviceMId
                 :type=tableType
                 :dateTimeRange="dateTimeRange" @cancel="isShowDetails = false"></lookTable>
    </div>
  </div>
</template>

<script>
import Cascader from '@/components/Cascader'
import fileDownload from "js-file-download";
import lookTable from './lookTable'
import recursion from '../../../util/recursion'
import moment from "moment";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "equipmentMaintenance",
    mixins:[toggleTableOperation],
  components: {
    lookTable,
    Cascader
  },
  data() {
    return {
      isShowDetails: false,
      ids: [],
      deviceMId: '',
      tableType: 1,
      searchParams: {},
      checkBtnPermission: {},
      total: 0,
      pageNum: 1,
      pageSize: 10,
      pageSizeOption: [10, 20, 30],
      categoryNameList: ['A', 'B', 'C'],
      deviceList: [],
      columns: [
        {
          type: "selection",
          minWidth: 60,
          align: "center",
          fixed: "left",
        },
        {
          title: `${this.$t('设备类别')}`,
          key: "deviceType",
          align: "center",
          minWidth: 160,
            resizable: true
          // render: (h, params) => {
          //   return h(
          //       "div",
          //       params.row.categoryName ? params.row.categoryName + '类' : ''
          //   );
          // },
        },
        {
          // title: `${ this.$t('maintenance.EquipmentName') }`,
          title: `${this.$t('preliminary.EquipmentName')}`,
          key: "deviceName",
          align: "center",
          minWidth: 160,
            resizable: true
        },
        {
          //title: `${ this.$t('maintenance.EquipmentNo') }`,
          title: `${this.$t('maintenance.EquipmentNo')}`,
          key: "deviceNo",
          align: "center",
          minWidth: 150,
            resizable: true
        },
        {
          // title: "公司名称",
          title: `${this.$t('spareParts.company')}`,
          key: "companyName",
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          // title: `${ this.$t('common.Installation') }`,
          title: `${this.$t('equipmentscrapped.Location')}`,
          key: "position4",
          align: "center",
          minWidth: 120,
            resizable: true
        },

        {
          // title: "平均故障间隔时间/MTBF（H）",
          title: `${this.$t('fault.MTBF')}`,
          key: "mtbf",
          align: "center",
          minWidth: 230,
            resizable: true
          // tooltip: true,
        },
        {
          //title: "平均维修时间/MTTR（H）",
          title: `${this.$t('fault.MTTR')}`,
          key: "mttr",
          align: "center",
          minWidth: 220,
            resizable: true
          // tooltip: true,
        },
        {
          // title: "维修次数",
          title: `${this.$t('fault.CumulativeNumberOfFailures')}`,
          key: "fixCount",
          align: "center",
          minWidth: 230,
            resizable: true
          // ellipsis: true
        },
        {
          // title: "净运行时间",
          title: `${this.$t('fault.NetRunningTime')}（H）`,
          key: "rumTimeDecimal",
          align: "center",
          minWidth: 210,
            resizable: true
          // ellipsis: true
        },
        {
          // title: "累计故障时间",
          title: `${this.$t('fault.CumulativeFailureTime')}（H）`,
          key: "repairTime",
          align: "center",
          minWidth: 230,
            resizable: true
          // ellipsis: true
        },
        // {
        //   // title: "累计故障次数",
        //   title: `${this.$t('fault.MaintenanceTimes')}`,
        //   key: "fixCount",
        //   align: "center",
        //   minWidth: 160,
        //   // ellipsis: true
        // },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          minWidth: 100,
          align: "center",
          fixed: 'right',
        },
      ],
      dataSource: [],
      dateTimeRange: [this.$moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD'), this.$moment(new Date()).format('YYYY-MM-DD')],
      companyList: [], // 所属公司
      orgList: [],
      orderArr:[]
    };
  },
  created() {

      this.getTableColumnsWidth(this.columns,'equipmentMaintenancepage1')

    this.changeNum();
    this.getCompany();
    this.getOrgList()
  },
  methods: {
    handleCasChange(val) {
      console.log(val)
      this.searchParams.orgCode = val[val.length - 1];
    },
    searchDevice(query) {
      this.axios({
        method: "get",
        url: "/dms/dmsDevice/deviceListByParams",
        params: {
          // orgCodes: this.searchParams.orgCodes || [],
          param: query
        },
      }).then((res) => {
        if (res.code === 200) {
          this.deviceList = res.data;
        }
      });
    },
    showLookTable(row) {
      this.deviceMId = row.deviceMId
      this.isShowDetails = true
    },
    getCompany() {
      this.axios({
        method: "get",
        url: "/basic/company/getCompanyListByUser",
      }).then((res) => {
        if (res.code === 200) {
          this.companyList = res.data
        }
      });
    },
    // 获取使用位置
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {level:1}
      }).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    //日期
    handleChangeDate(val) {
      this.dateTimeRange = val
    },
    reset(){
      this.searchParams = {};
      this.dateTimeRange = [this.$moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD'), this.$moment(new Date()).format('YYYY-MM-DD')],
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {
      //查询列表
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        companyId: this.searchParams.companyId,
        orgCodes: this.searchParams.orgCodes || [],
        deviceName: this.searchParams.deviceName,
        deviceNo: this.searchParams.deviceNo,
        categoryName: this.searchParams.categoryName && this.searchParams.categoryName.replace('类', ''),
        startTime: moment(this.dateTimeRange[0]).format('YYYY-MM-DD 00:00:00'),
        endTime: moment(this.dateTimeRange[1]).format('YYYY-MM-DD 23:59:59'),
      };
      this.axios({
        method: "post",
        url: "/dms/statistical/deviceRepairList",
        data: params,
      }).then((res) => {
        if (res.code === 200) {
          this.dataSource = res.data.list;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    onSelectChange(selectionData) {
      this.ids = selectionData.map(v => v.id);
    },
    //导出
    exportTemplateClick() {
      let params = {
        // pageNo: this.pageNum,
        // pageSize: this.pageSize,
        deviceMIds: this.ids,
        companyId: this.searchParams.companyId,
        orgCodes: this.searchParams.orgCodes || [],
        deviceName: this.searchParams.deviceName,
        deviceNo: this.searchParams.deviceNo,
        categoryName: this.searchParams.categoryName,
        startTime: moment(this.dateTimeRange[0]).format('YYYY-MM-DD 00:00:00'),
        endTime: moment(this.dateTimeRange[1]).format('YYYY-MM-DD 23:59:59'),
      };
      // const filName = "设备维修报表";
      const filName = `${this.$t('fault.EquipmentMaintenanceReport')}`;
      this.axios({
        method: "post",
        url: "/dms/statistical/deviceRepairListExport",
        responseType: "blob",
        data: params,
      }).then((res) => {
        fileDownload(res, filName + ".xlsx");
      });
    },

  },
};
</script>

<style lang="scss" scoped>

</style>


